package com.bub.pay.framework.common.util;

import com.alibaba.fastjson.JSON;
import com.bub.pay.framework.common.constant.SystemConstants;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.config.SocketConfig;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * HttpHelper
 *
 * @author Leo
 * @ClassName: HttpHelper
 * @Description:
 */
@Component
public class HttpHelper {

    private static final Logger log = LoggerFactory.getLogger(HttpHelper.class);

    private static CloseableHttpClient httpClient;

    /**
     * 是否启用代理
     */
    private static boolean enableProxy = false;

    @Value("${http-helper.proxy:''}")
    public void setEnableProxy(String enableProxy) {
        HttpHelper.enableProxy = StringUtils.isNotBlank(enableProxy) && enableProxy.equals("enable");
        if (HttpHelper.enableProxy) {
            log.info("######### enableProxy #########");
        } else {
            log.info("######### disableProxy #########");
        }
    }

    static {
        RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
        // 客户端和服务器建立连接的timeout
        requestConfigBuilder.setConnectTimeout(30000);
        // 从连接池获取连接的timeout
        requestConfigBuilder.setConnectionRequestTimeout(30000);
        // 连接建立后，request没有回应的timeout
        requestConfigBuilder.setSocketTimeout(30000);
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(200);
        connectionManager.setDefaultMaxPerRoute(20); // 同一路由最多100并发

        HttpClientBuilder clientBuilder = HttpClientBuilder.create();
        clientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());
        clientBuilder.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(30000).build());
        clientBuilder.setConnectionManager(connectionManager);
        // 连接建立后，request没有回应的timeout
        clientBuilder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy());
        httpClient = clientBuilder.build();
    }

    public static String getMethod(String url) {
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response;
        try {
            response = httpClient.execute(httpGet);
            return IOUtils.toString(response.getEntity().getContent(), SystemConstants.DEFAULT_CODE);
        } catch (Exception ex) {
            log.error("http error:", ex);
        } finally {
            if (httpGet != null) {
                httpGet.releaseConnection();
            }
        }
        return null;
    }

    public static String postMethod(String url, Map<String, Object> param) throws IOException {
        log.info("HTTP请求URL:" + url);
        log.info("HTTP请求参数:" + JSON.toJSONString(param));
        HttpPost httpost = new HttpPost(url);
        try {
            StringEntity entity = new StringEntity(JSON.toJSONString(param), ContentType.APPLICATION_JSON);
            httpost.setEntity(entity);
            CloseableHttpResponse response = httpClient.execute(httpost);
            String result = IOUtils.toString(response.getEntity().getContent(), SystemConstants.DEFAULT_CODE);
            log.info("HTTP返回结果:" + result);
            return result;
        } catch (Exception ex) {
            log.error("http error:", ex);
        }
        if (httpost != null) {
            httpost.releaseConnection();
        }
        return null;
    }


    /**
     * 发送POST请求（表单形式）
     *
     * @param url    请求地址
     * @param params 参数
     * @return 结果
     */
    public static String post(String url, Map<String, String> params) {
        log.info("HTTP请求URL:" + url);
        log.info("HTTP请求参数:" + JSON.toJSONString(params));
        HttpPost httpPost = new HttpPost(url);

        try {
            List<BasicNameValuePair> pairList = params.entrySet().stream().map(e -> new BasicNameValuePair(e.getKey(), e.getValue())).collect(Collectors.toList());
            httpPost.setEntity(new UrlEncodedFormEntity(pairList, "UTF-8"));
            CloseableHttpResponse response = httpClient.execute(httpPost);
            String result = IOUtils.toString(response.getEntity().getContent(), SystemConstants.DEFAULT_CODE);
            log.info("HTTP返回结果:" + result);
            return result;
        } catch (Exception e) {
            log.error("http error:", e);
        } finally {
            httpPost.releaseConnection();
        }

        return null;
    }

    /**
     * 发送POST请求（JSON形式）
     *
     * @param url     请求地址
     * @param dataStr 参数
     * @return 结果
     */
    public static String post(String url, String dataStr) {
        log.info("HTTP请求URL:" + url);
        log.info("HTTP请求参数:" + dataStr);
        HttpPost httpPost = new HttpPost(url);

        try {
            StringEntity entity = new StringEntity(dataStr, "utf-8");
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            CloseableHttpResponse response = httpClient.execute(httpPost);
            String result = IOUtils.toString(response.getEntity().getContent(), SystemConstants.DEFAULT_CODE);
            log.info("HTTP返回结果:" + result);
            return result;
        } catch (Exception e) {
            log.error("http error:", e);
        } finally {
            httpPost.releaseConnection();
        }

        return null;
    }

    /**
     * 获取代理请求配置
     *
     * @param proxyIp   代理IP
     * @param proxyPort 代理端口
     * @return 请求配置
     */
    private static RequestConfig getProxyRequestConfig(String proxyIp, int proxyPort) {
        if (StringUtils.isBlank(proxyIp)) {
            throw new RuntimeException("代理IP为空");
        }
        if (proxyPort <= 0) {
            throw new RuntimeException("代理Port非法");
        }
        HttpHost proxy = new HttpHost(proxyIp, proxyPort);
        return RequestConfig.custom()
                .setProxy(proxy)
                .setConnectTimeout(10000)
                .setSocketTimeout(10000)
                .setConnectionRequestTimeout(3000)
                .build();
    }

    /**
     * 通过代理发送POST请求（JSON形式）
     *
     * @param url         请求地址
     * @param requestBody 参数
     * @return 结果
     */
    public static String postJSONByProxy(String url, String requestBody, String proxyIp, int proxyPort) {
        return sendJsonByProxy(new HttpPost(url), requestBody, proxyIp, proxyPort);
    }

    /**
     * 通过代理发送请求（JSON形式）
     *
     * @param requestBase 请求方式
     * @param requestBody 参数
     * @return 结果
     */
    public static String sendJsonByProxy(HttpRequestBase requestBase, String requestBody, String proxyIp, int proxyPort) {
        log.info("sendJsonByProxy[{}:{}],requestBase:{},requestBody:{}", proxyIp, proxyPort, requestBase, requestBody);
        if (enableProxy) {
            RequestConfig proxyRequestConfig = getProxyRequestConfig(proxyIp, proxyPort);
            requestBase.setConfig(proxyRequestConfig);
        }
        try {
            StringEntity entity = new StringEntity(requestBody, "utf-8");
            entity.setContentType("application/json");
            entity.setContentEncoding("UTF-8");
            if (StringUtils.isNotBlank(requestBody)) {
                ((HttpEntityEnclosingRequestBase) requestBase).setEntity(entity);
            }
            CloseableHttpResponse response = httpClient.execute(requestBase);
            String result = IOUtils.toString(response.getEntity().getContent(), SystemConstants.DEFAULT_CODE);
            log.info("sendJsonByProxy[{}:{}],requestBase:{},result:{}", proxyIp, proxyPort, requestBase, result);
            return result;
        } catch (Exception e) {
            log.error("sendJsonByProxy error:", e);
        } finally {
            requestBase.releaseConnection();
        }
        return null;
    }

    public static String getByProxy(String url, Map<String, String> headMaps, String proxyIp, int proxyPort) {
        log.info("getByProxy[{}:{}],url:{}", proxyIp, proxyPort, url);
        HttpGet httpGet = new HttpGet(url);
        if (enableProxy) {
            RequestConfig proxyRequestConfig = getProxyRequestConfig(proxyIp, proxyPort);
            httpGet.setConfig(proxyRequestConfig);
        }
        CloseableHttpResponse resp;
        try {
            headMaps.forEach((k, v) -> httpGet.setHeader(k, v));
            resp = httpClient.execute(httpGet);
            return IOUtils.toString(resp.getEntity().getContent(), SystemConstants.DEFAULT_CODE);
        } catch (Exception e) {
            log.error("get请求异常:", e);
        } finally {
            if (httpGet != null) {
                httpGet.releaseConnection();
            }
        }
        return null;
    }

    /**
     * 通过代理发送POST请求（表单形式）
     *
     * @param url    请求地址
     * @param params 参数
     * @return 结果
     */
    public static String postFormByProxy(String url, Map<String, String> params, String proxyIp, int proxyPort) {
        return postFormByProxy(url, params, proxyIp, proxyPort, SystemConstants.DEFAULT_CODE);
    }

    /**
     * 通过代理发送POST请求（表单形式）
     *
     * @param url    请求地址
     * @param params 参数
     * @return 结果
     */
    public static String postFormByProxy(String url, Map<String, String> params, String proxyIp, int proxyPort, String charset) {
        log.info("postFormByProxy[{}:{}],url:{},params:{}", proxyIp, proxyPort, url, params);
        HttpPost httpPost = new HttpPost(url);
        try {
            List<BasicNameValuePair> pairList = params.entrySet().stream().map(e -> new BasicNameValuePair(e.getKey(), e.getValue())).collect(Collectors.toList());
            httpPost.setEntity(new UrlEncodedFormEntity(pairList, "UTF-8"));
            if (enableProxy) {
                RequestConfig proxyRequestConfig = getProxyRequestConfig(proxyIp, proxyPort);
                httpPost.setConfig(proxyRequestConfig);
            }
            CloseableHttpResponse response = httpClient.execute(httpPost);
            String result = IOUtils.toString(response.getEntity().getContent(), charset);
            log.info("postFormByProxy[{}:{}],url:{},result:{}", proxyIp, proxyPort, url, result);
            return result;
        } catch (Exception e) {
            log.error("postJSONByProxy error:", e);
        } finally {
            httpPost.releaseConnection();
        }
        return null;
    }

}
